package com.example.lotterysystem.common.utils;

import com.fasterxml.jackson.core.JacksonException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.List;
import java.util.concurrent.Callable;

public class JacksonUtil {
    private JacksonUtil(){

    }

    private final static ObjectMapper objectMapper = new ObjectMapper();

    private static ObjectMapper getObjectMapper(){
        return objectMapper;
    }

    private static <T> T tryParse(Callable<T> parser){
        return tryParse(parser, JacksonException.class);
    }

    private static <T> T tryParse(Callable<T> parser, Class<? extends Exception> e){
        try {
            return parser.call();
        } catch (Exception exception){
            if(e.isAssignableFrom(exception.getClass())) {
                throw new RuntimeException();
            }
            throw new IllegalStateException(exception);
        }
    }

    /**
     * 序列化
     */
    public static String writeValueAsString(Object object){
        return JacksonUtil.tryParse(() -> {
            return objectMapper.writeValueAsString(object);
        });
    }

    /**
     * 反序列化
     */
    public static <T> T readValue(String str, Class<T> type){
        return JacksonUtil.tryParse(() -> {
           return objectMapper.readValue(str, type);
        });
    }

    /**
     * 反序列化 List
     */
    public static <T> T readListValue(String str, Class<?> type){
        JavaType javaType = objectMapper.getTypeFactory().
                constructParametricType(List.class, type);
        return JacksonUtil.tryParse(() -> {
            return objectMapper.readValue(str, javaType);
        });
    }

}
